<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        /* html {
            height: 100vh;
        } */
        body {
            height: 100vh;
            background-color: gray;
        }
        div {
            position: absolute;
            /* top: 200px;
            left: 200px; */
            width: 100px;
            height: 100px;
            background-color: pink;
            border: 1px solid #000;
            transition: .5s all;
        }
    </style>
</head>

<body>
    <div></div>
    <script>
        var div = document.querySelector('div')
        var body = document.querySelector('body')
        console.log(body);
        var tops = 0
       
        var lefts = 0
        
        document.addEventListener('keydown', function (e) {

            // var a = body.offsetHeight - div.offsetHeight
        //    console.log(a);
            if (e.keyCode == 87) { //w
                tops -= 155
                if ( tops < 0) {
                    tops = 0               
                }
                div.style.top = tops + 'px'
            } else if (e.keyCode == 83) { //s
                tops += 155
               
                if ( tops > body.offsetHeight - div.offsetHeight) {
                    tops = body.offsetHeight - div.offsetHeight            
                } 
                    div.style.top = tops + 'px'
          
            } else if (e.keyCode == 65) { //a
                lefts -= 155
                if (lefts < 0) {
                    lefts = 0
                    
                }
                div.style.left = lefts + 'px'
            } else if (e.keyCode == 68) { //d
                lefts += 155
                if (lefts > body.offsetWidth - div.offsetWidth) {
                    lefts = body.offsetWidth - div.offsetWidth
                   
                }
                div.style.left = lefts + 'px'
            }
        })
    </script>
</body>

</html>